package com.qq2008.game.mojie.controller;

import com.qq2008.game.mojie.annotation.AuthPassport;
import com.qq2008.game.mojie.form.JSONResult;
import com.qq2008.game.mojie.form.Message;
import com.qq2008.game.mojie.form.Result;
import com.qq2008.game.mojie.jdo.R;
import com.qq2008.game.mojie.jdo.User;
import com.qq2008.game.mojie.redis.RedisUtil;
import com.qq2008.game.mojie.service.UserService;
import com.qq2008.game.mojie.utils.CommonUtil;
import com.qq2008.game.mojie.utils.CookieUtil;
import com.qq2008.game.mojie.utils.HashUtil;
import com.qq2008.game.mojie.utils.NowTimeUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Pattern;

// 用户
@RestController
public class UserController {

    @Resource
    RedisUtil redisUtil;

    // id检测, 4位+
    private final static String REGEX_LOGIN_ID = "^[A-Za-z0-9\\u4e00-\\u9fa5]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$";
    // 登录名, 6-15位字符, 字符包含大小写字母和数字
    private final static String REGEX_LOGIN_NAME = "^[A-Za-z0-9\\u4e00-\\u9fa5]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$";
    // 密码, 6-15位字符, 字符包含大小写字母和数字和特殊符号-#@！
    private final static String REGEX_PASSWORD = "^[0-9a-zA-Z-#@!]{6,15}$";
    // cookie有效期, 3个小时
    private final static int COOKIE_AGE = 3 * 60 * 60;

    @Resource
    private UserService userService;

//    // 登录页面
//    @RequestMapping(value = {"", "/", "/login"}, method = RequestMethod.GET)
//    public String login(Model model, HttpServletRequest request) {
//        model.addAttribute("returnUrl", request.getParameter("returnUrl"));
//        return "user_login_jq2";
//    }

    // 登录
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public R<User> doLogin(Model model,
                           HttpSession session, HttpServletRequest request, HttpServletResponse response,
                           @RequestBody User user) {
        Map<String, Object> param = new HashMap<>();
        JSONResult result = JSONResult.jsonResult(0, false, JSONResult.CODE_ERROR, "登陆失败", null, null);
        param.put("loginName", user.getLoginName());
        //密码校验
        if (!Pattern.compile(REGEX_PASSWORD).matcher(user.getPassword()).find()) {
            result.setMessage("密码格式不正确");
            result.setCode(JSONResult.CODE_FORMAT_ERROR);
            model.addAttribute("error", result);
            return R.failed("密码格式不正确");
        }

//        if (Pattern.compile(REGEX_LOGIN_ID).matcher(loginName).find()) {
//            param.put("userID", loginName);
//        } else {
//            param.put("loginName", loginName);
//        }
        param.put("loginName", user.getLoginName());
        param.put("password", HashUtil.toMd5(user.getPassword()));
        User userInfo = userService.get(param);

        if (userInfo != null) {
            // 添加登陆信息至cookie
            CookieUtil.setCookie(response, "JSESSIONID", session.getId() + "", COOKIE_AGE);
            CookieUtil.setCookie(response, "uuid", HashUtil.desEncode(user.getUnionID() + ""), COOKIE_AGE);
            CookieUtil.setCookie(response, "hash", HashUtil.toMd5(user.getLoginName() + "," + user.getPassword()), COOKIE_AGE);
            // 添加登陆信息至session
            session.setAttribute("user", userInfo);

            Map<String, Object> logData = new HashMap<>();
            logData.put("unionID", user.getUnionID());
            logData.put("loginDate", CommonUtil.getTimestamp());
//            userService.logLogin(logData);
            //
            Message message = new Message("登录成功", "登录成功<br />", "进入游戏", "/mojie");
            String url = (String) request.getSession().getAttribute("returnUrl");
            request.getSession().removeAttribute("returnUrl");
            if (StringUtils.isNotEmpty(url)) {
                message.setMessage("登录成功<br />正在返回登录前界面...");
                message.setUrl(url);
            }
            model.addAttribute("message", message);
            //该玩家在线信息存入缓存,并记录的在线时间
            redisUtil.set(user.getLoginName(), NowTimeUtil.nowtime());
            return R.success(user);
        } else {
            result.setMessage("账户和密码不匹配");
            model.addAttribute("error", result);
            return R.failed("账户和密码不匹配");
        }
    }

    // 登录成功
    @RequestMapping(value = "/loginSuccess", method = RequestMethod.GET)
    public String loginSuccess(Model model) {
        model.addAttribute("pageTitle", "登陆成功");

        return "user_login_success";
    }

    // 注册页面
    @RequestMapping(value = "/register", method = RequestMethod.GET)
    public String register(Model model) {
        model.addAttribute("pageTitle", "注册");
        return "user_register_jq2";
    }

    // 注册
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public String doRegister(Model model,
                             @RequestParam(value = "name") String loginName,
                             @RequestParam(value = "password") String password) {
        Map<String, Object> param = new HashMap<>();
        JSONResult result = JSONResult.jsonResult(0, false, Result.CODE_ERROR, "注册异常", null, null);
        // 登录名校验
        param.put("loginName", loginName);
        param.put("checkFlag", "loginName");
        User checkUser = userService.get(param);
        if (null != checkUser) {
            result.setMessage("该账户已存在，请重新注册");
            model.addAttribute("error", result);
            return "user_register_jq";
        }

        // userID校验
        boolean idExisted = true;
        int userID;
        List<Integer> allID = userService.allID();
        do {
            userID = CommonUtil.randomInt(1100, 10000);
            if (!allID.contains(userID)) {
                idExisted = false;
            }
        } while (userID == 0 || idExisted);

        User user = new User(loginName, HashUtil.toMd5(password), "11111111111");
        user.setUserID(userID);
        user.setRegisterTime(CommonUtil.getTimestamp());
        user.setNickName("game_" + userID);
        user.setState(1);
        user.setUnionID(UUID.randomUUID().toString());
        user.setHeadImg("header_1.png");
        int res = userService.register(user);

        if (res > 0) {
            return "redirect:/login";
        } else {
            model.addAttribute("error", result);
            return "user_register_jq";
        }

    }

    // 注销登录
    @RequestMapping("quit")
    public String quit(HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        // 清理session
        session.invalidate();
        // 清理cookie
        CookieUtil.removeCookie(request, response, "id");
        CookieUtil.removeCookie(request, response, "hash");
        return "redirect:/login";
    }

    @RequestMapping("userCenter")
    @AuthPassport
    public String usenCenter(HttpSession session, Model model) {
        Map<String, Object> params = new HashMap<>();
        User user = (User) session.getAttribute("user");
        params.put("userId", user.getUserID());
//        List<UserGame> gameList = userGameService.list(params);
//        model.addAttribute("gameList", gameList);
        model.addAttribute("pageTitle", "个人中心");
        return "user_center";
    }
}
